import 'dart:async';

import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';
import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/we3_method.dart';
import 'package:aichat_flutter_wallet/module/module_browser/widget/select_network.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/pages/dapp_history_page.dart';
import 'package:aichat_flutter_wallet/module/module_dapp/provider/dapp_provider.dart';
import 'package:aichat_flutter_wallet/module_common/provider/nav_key.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';

class BrowserSearchWidget extends StatefulWidget {
  Function? onClose;
   BrowserSearchWidget({super.key, required this.url,this.onClose});

  final String url;

  @override
  State<BrowserSearchWidget> createState() => _BrowserSearchWidgetState();
}

class _BrowserSearchWidgetState extends State<BrowserSearchWidget> {
  bool isLove = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchData();
  }

  setLove(bool value) {
    setState(() {
      isLove = value;
    });
  }

  @override
  void fetchData() {
    try {
      final favoriteDApp = Provider.of<DAppProvider>(context, listen: false);
      final List<DAppBean> favoriteDAppList =
          favoriteDApp.favoriteDAppList.toList();
      final DAppBean? favoriteItem = favoriteDAppList.length > 0
          ? favoriteDAppList
              .firstWhereOrNull((element) => element.url == widget.url)
          : null;
      bool isFavorite = favoriteItem != null;
      // BrowserProvider browserProvider;
      // browserProvider = Provider.of<BrowserProvider>(context, listen: false);
      // browserProvider.setLove(isFavorite);
      setLove(isFavorite);

      // if (isLove != isFavorite) {
      //   setState(() {
      //     isLove = isFavorite;
      //   });
      // }
    } catch (e) {
      kaiPrint(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<BrowserProvider>(builder: (context, browser, child) {
      return Container(
        height: 44.w,
        padding: EdgeInsets.only(left: 20, right: 15),
        child: Row(
          children: [
            InkWell(
              overlayColor: MaterialStateProperty.resolveWith((states) {
                return Colors.transparent;
              }),
              onTap: () {
                browser.back(widget.onClose);
              },
              child: Image(
                image: AssetImage('assets/images/dapp/back.png'),
                height: 20.w,
                width: 20.w,
              ),
            ),
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                if(widget.onClose!=null){
                  widget.onClose!();
                  return;
                }
                browser.clearConnect();
                Timer(Duration.zero, () {
                  Navigator.of(context).pushReplacement(MaterialPageRoute(
                    builder: (_) {
                      return DAppHistoryPage();
                    },
                  ));
                });
              },
              behavior: HitTestBehavior.translucent,
              child: Container(
                padding: EdgeInsets.only(top: 10, bottom: 10, right: 5),
                child: Image(
                  image: AssetImage('assets/images/dapp/close.png'),
                  height: 20.w,
                  width: 20.w,
                ),
              ),
            ),
            SizedBox(
              width: 5.w,
            ),
            Expanded(
              child: Container(
                height: 34.w,
                padding: EdgeInsets.symmetric(horizontal: 15),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: AppColors.c_F6F6F6),
                child: Row(
                  children: [
                    Image(
                      image: AssetImage('assets/images/dapp/lock.png'),
                      height: 12.w,
                      width: 12.w,
                    ),
                    SizedBox(
                      width: 7.w,
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          if(widget.onClose!=null){
                            return;
                          }
                          Navigator.of(context)
                              .pushReplacement(MaterialPageRoute(
                            builder: (_) {
                              return DAppHistoryPage(
                                url: widget.url,
                              );
                            },
                          ));
                          // Navigator.of(context)
                          //     .pushReplacementNamed(Routes.dAppHistoryRoute);
                        },
                        child: Text(
                          widget.url,
                          style: TextStyle(
                            overflow: TextOverflow.ellipsis,
                          ),
                          maxLines: 1,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        browser.love(widget.url, callback: (value) {
                          setLove(value);
                        });
                      },
                      behavior: HitTestBehavior.translucent,
                      child: Container(
                        padding: EdgeInsets.only(left: 5, top: 10, bottom: 10),
                        child: !isLove
                            ? Image(
                                image:
                                    AssetImage('assets/images/dapp/star.png'),
                                height: 16.w,
                                width: 16.w,
                                fit: BoxFit.contain,
                              )
                            : Image(
                                image: AssetImage(
                                    'assets/images/dapp/star-active.png'),
                                height: 16.w,
                                width: 16.w,
                              ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(
              width: 10.w,
            ),
            GestureDetector(
              onTap: () {
                Wallet? wallet =
                    NavKey.getContext().read<WalletInfoNotifier>().wallet;
                if (wallet == null) return;
                String walletName = browser.selectChain == null
                    ? ''
                    : browser.selectChain!.shortName;
                Web3MethodCall.selectNetwork(
                        child: SelectNetwork(selectWalletName: walletName))
                    .then((value) {
                  if (value != null) {
                    Chain chain = value['chain'];
                    NodeInfo nodeInfo = value['node'];
                    // 连接的切换网络
                    if (browser.isConnectWallet) {
                      browser.setSelectChain(value);
                      Web3MethodCall.changeNetwork(
                          chainId: chain.evmInfo!.chainId,
                          nodeUrl: nodeInfo.url);
                    } else {
                      Web3MethodCall.changeNetConfig(
                          chainId: chain.evmInfo!.chainId,
                          nodeUrl: nodeInfo.url);
                    }
                  }
                });
              },
              child: browser.selectChain == null
                  ? Image(
                      image: AssetImage('assets/images/dapp/browser.png'),
                      height: 30.w,
                      width: 30.w,
                    )
                  : ClipRRect(
                      borderRadius: BorderRadius.circular(15),
                      child: PublicImage(
                        image: browser.selectChain!.logo,
                        height: 30.w,
                        width: 30.w,
                      ),
                    ),
            )
          ],
        ),
      );
    });

    // return
  }
}
